// newapi/repairProgressRoutes.js
const express = require('express');
const router = express.Router();
const RepairProgress = require('../../models/newmodels/repairProgressSchema'); // 维修进度信息文档

// 创建一个新的维修进度记录
router.post('/repairProgresses', async (req, res) => {
  console.log(req.body);

  try {
    const repairProgress = new RepairProgress(req.body);
    await repairProgress.save();
    res.status(200).send({ code: '200', msg: '维修进度信息插入成功', data: repairProgress });
  } catch (error) {
    res.status(400).send({ code: '400', msg: '维修进度信息插入失败', data: error });
  }
});

// 获取所有维修进度记录
router.get('/repairProgresses', async (req, res) => {
  try {
    const repairProgresses = await RepairProgress.find().populate('repairId userId')//添加这个信息可以把用户的信息和维修状态的信息一起返回
    // const repairProgresses = await RepairProgress.find();  //.populate('repairId userId')添加这个信息可以把用户的信息和维修状态的信息一起返回
    res.status(200).send({ code: '200', msg: '查询数据成功', data: repairProgresses });
  } catch (error) {
    res.status(500).send({ code: '500', msg: '查询数据失败', data: error });
  }
});

//依据ID查询维修进度
// 根据机器ID获取维修进度记录
router.get('/repairProgressesByMachineId', async (req, res) => {
  const machineId = req.query.machineId; // 假设前端通过查询参数传递机器ID
  console.log(machineId);


  if (!machineId) {
    return res.status(400).send({ code: '400', msg: '缺少机器ID参数', data: null });
  }

  try {
    const repairProgresses = await RepairProgress.find({ machineId }).populate('userId');
    res.status(200).send({ code: '200', msg: '查询数据成功', data: repairProgresses });
  } catch (error) {
    res.status(500).send({ code: '500', msg: '查询数据失败', data: error });
  }
});


// 更新单个维修进度记录
router.put('/repairProgresses/:id', async (req, res) => {
  try {
    const repairProgress = await RepairProgress.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
    if (!repairProgress) {
      return res.status(404).send({ code: '404', msg: '没有找到该维修进度记录', data: null });
    }
    res.status(200).send({ code: '200', msg: '更新维修进度信息成功', data: repairProgress });
  } catch (error) {
    res.status(400).send({ code: '400', msg: '更新维修进度信息失败', data: error });
  }
});

// 删除单个维修进度记录
router.delete('/repairProgresses/:id', async (req, res) => {
  try {
    const repairProgress = await RepairProgress.findByIdAndDelete(req.params.id);
    if (!repairProgress) {
      return res.status(404).send({ code: '404', msg: '没有找到要删除的维修进度记录', data: null });
    }
    res.status(200).send({ code: '200', msg: '维修进度信息删除成功', data: repairProgress });
  } catch (error) {
    res.status(500).send({ code: '500', msg: '维修进度信息删除失败', data: error });
  }
});

module.exports = router;